package com.wangzh.concurrent.lock.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {
    public static void main(String[] args) {
//        extracted();

//        正常引用都是一个个对象，不是基本类型的包装类。比如Integer，缓存范围是-128··127。
        AtomicStampedReference<Integer> reference = new AtomicStampedReference(10, 1);

        new Thread(() ->{
            System.out.println("a1"+reference.getStamp());
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("a2=>"+reference.compareAndSet(10, 12, reference.getStamp(), reference.getStamp() + 1));
            System.out.println("a2=>"+reference.compareAndSet(12, 10, reference.getStamp(), reference.getStamp() + 1));

        },"a").start();
        new Thread(() ->{
            System.out.println("b1"+reference.getStamp());
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("b2=》"+reference.compareAndSet(10, 12, reference.getStamp(), reference.getStamp() + 1));
        },"b").start();
    }

    private static void extracted() {
        AtomicInteger atomicInteger = new AtomicInteger(100);

//        捣乱的修改，这就是ABA问题
        atomicInteger.compareAndSet(100, 105);
        atomicInteger.compareAndSet(105, 100);

//        本身期望的操作，上面的修改对我来说是不知道的。不希望我不知道
        atomicInteger.compareAndSet(100, 101);
    }
}
